package com.learn.tomcat.processor;

import com.learn.tomcat.server.Request;
import com.learn.tomcat.server.Response;
import com.learn.tomcat.util.Constans;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

public class ServletProcessor implements Processor {
    @Override
    public void process(Request request, Response response) {
        String uri = request.getUri();
        String servletName = uri.substring(uri.lastIndexOf("/") + 1);
        System.out.println("servletName: " + servletName);
        URLClassLoader loader = null;
        try {
            URL[] urls = new URL[1];
            URLStreamHandler streamHandler = null;
            File classPath = new File(Constans.WEB_ROOT);
            String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator).toString());
            urls[0] = new URL(null, repository, streamHandler);
            loader = new URLClassLoader(urls);
            Class<?> clazz = loader.loadClass("com.learn.tomcat.servlet." + servletName);
            Servlet servlet = (Servlet) clazz.newInstance();
            System.out.println("servlet: " + servlet);
            System.out.println("servlet service()");
            servlet.service(request, response);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } finally {
            if (loader != null) {
                try {
                    loader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
